const fs = require('fs');
const path = require('path');
const { queryDatabase, insertDatabase, updateDatabase, deleteDatabase, executeTransaction } = require('../queue-client');

// 检查指定货位是否已在TaskList中存在且未下发
async function checkTaskExists(row, col, layer) {
  try {
    const checkSql = fs.readFileSync(path.join(__dirname, '../check-task-exists.sql'), 'utf8');
    const checkParams = [row, col, layer];
    const existingTasks = await queryDatabase(checkSql, checkParams);
    return existingTasks.length > 0;
  } catch (error) {
    console.error('检查任务是否存在失败:', error);
    throw error;
  }
}

// 插入任务记录
async function insertTask(taskData) {
  try {
    const sql = `
      INSERT INTO TaskList (Task_No, Job_Style, Unload_Line, Unload_Col, Unload_Layer, is_issued, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
    `;
    
    const params = [
      taskData.Task_No || 0,
      taskData.Job_Style || 0,
      taskData.Unload_Line || 0,
      taskData.Unload_Col || 0,
      taskData.Unload_Layer || 0,
      taskData.is_issued || 0
    ];
    
    const result = await insertDatabase(sql, params);
    console.log(`✅ 插入任务记录`);
    return { success: true, taskId: result.lastInsertRowid, message: '任务记录插入成功' };
  } catch (error) {
    console.error('插入任务记录失败:', error);
    return { success: false, message: '插入任务记录失败: ' + error.message };
  }
}



// 查询所有任务记录
async function getAllTasks() {
  try {
    const sql = `
      SELECT * FROM TaskList
      ORDER BY created_at DESC
    `;
    
    const rows = await queryDatabase(sql);
    return rows;
  } catch (error) {
    console.error('查询任务记录失败:', error);
    throw error;
  }
}

// 根据任务号查询任务记录
async function getTaskByTaskNo(taskNo) {
  try {
    const sql = `
      SELECT * FROM TaskList
      WHERE Task_No = ?
      ORDER BY created_at DESC
    `;
    
    const rows = await queryDatabase(sql, [taskNo]);
    return rows;
  } catch (error) {
    console.error('根据任务号查询任务记录失败:', error);
    throw error;
  }
}

// 更新任务记录
async function updateTask(taskId, taskData) {
  try {
    const sql = `
      UPDATE TaskList 
      SET Task_No = ?, Job_Style = ?, Unload_Line = ?, Unload_Col = ?, Unload_Layer = ?, is_issued = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;
    
    const params = [
      taskData.Task_No || 0,
      taskData.Job_Style || 0,
      taskData.Unload_Line || 0,
      taskData.Unload_Col || 0,
      taskData.Unload_Layer || 0,
      taskData.is_issued || 0,
      taskId
    ];
    
    await updateDatabase(sql, params);
    console.log(`✅ 更新任务记录，ID: ${taskId}`);
  } catch (error) {
    console.error('更新任务记录失败:', error);
    throw error;
  }
}

// 更新任务下发状态
async function updateTaskIssuedStatus(taskId, isIssued) {
  try {
    console.log(`🔄 更新任务下发状态，任务ID: ${taskId}, 状态: ${isIssued ? '已下发' : '未下发'}`);
    
    const sql = `
      UPDATE TaskList 
      SET is_issued = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;
    
    const params = [isIssued ? 1 : 0, taskId];
    
    const result = await updateDatabase(sql, params);
    console.log(`✅ SQL执行结果，更改行数: ${result.changes}`);
    console.log(`✅ 更新任务下发状态，ID: ${taskId}, 状态: ${isIssued ? '已下发' : '未下发'}`);
  } catch (error) {
    console.error('更新任务下发状态失败:', error);
    throw error;
  }
}

// 删除任务记录
async function deleteTask(taskId) {
  try {
    const sql = 'DELETE FROM TaskList WHERE id = ?';
    await deleteDatabase(sql, [taskId]);
    console.log(`✅ 删除任务记录，ID: ${taskId}`);
  } catch (error) {
    console.error('删除任务记录失败:', error);
    throw error;
  }
}

module.exports = {
  insertTask,
  getAllTasks,
  getTaskByTaskNo,
  updateTask,
  updateTaskIssuedStatus,
  deleteTask,
  checkTaskExists
};